package com.huawei.orderservice.service.impl;


import com.huawei.common.pojo.Result;
import com.huawei.common.pojo.pay;
import com.huawei.common.pojo.updateMoney;
import com.huawei.common.utils.SnowflakeIdWorker;
import com.huawei.common.utils.ThreadLocalUtil;
import com.huawei.orderservice.client.ItemClient;
import com.huawei.orderservice.client.UserClient;
import com.huawei.orderservice.mapper.OrderMapper;
import com.huawei.orderservice.pojo.dto.OrderDTO;
import com.huawei.orderservice.pojo.dto.OrderDetailDTO;
import com.huawei.orderservice.pojo.dto.OrderUpdateDTO;
import com.huawei.orderservice.pojo.entity.Order;
import com.huawei.orderservice.pojo.entity.OrderDetail;
import com.huawei.orderservice.properties.SnowFlakeProperties;
import com.huawei.orderservice.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private SnowFlakeProperties snowFlakeProperties;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private ItemClient itemClient;
    @Autowired
    private UserClient userClient;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public Result createOrder(OrderDTO order) {
        List<OrderDetail> orderDetail = new ArrayList<>();
        Order orders = new Order();
        String[] userInfo = ThreadLocalUtil.get();
        BeanUtils.copyProperties(order,orders);
        orders.setCreateTime(LocalDateTime.now());
        orders.setUserId(Long.parseLong(userInfo[0]));
        SnowflakeIdWorker idWorker = new SnowflakeIdWorker(snowFlakeProperties.getWorkId(), snowFlakeProperties.getDataCenterId());
        long id = idWorker.nextId();
        orders.setId(id);
        System.out.println(orders);
        orderMapper.addOrder(orders);

        List<OrderDetailDTO> ordersDetails = order.getOrdersDetails();
        for (OrderDetailDTO orderdetaildto : ordersDetails) {
            OrderDetail temp = new OrderDetail();
            BeanUtils.copyProperties(orderdetaildto, temp);
            temp.setOrderId(id);
            orderDetail.add(temp);
        }
        System.out.println(orderDetail);
        orderMapper.addOrderDetail(orderDetail);


        return new Result(0, "下单成功", id);
    }

    @Override
    public Result updateOrder(OrderUpdateDTO order) {
        orderMapper.updateOrder(order);
        return new Result(0, "修改订单信息成功", null);
    }

    @Override
    @Transactional
    public Result payment(Long id) {
        List<OrderDetail> orderDetail = orderMapper.getOrderDetail(id);
        int sum = 0;
        String[] userInfo = ThreadLocalUtil.get();
        for (OrderDetail order : orderDetail) {
            Long itemId = order.getItemId();
            int num = order.getItemNumber();
            //int price = orderMapper.getItemPrice(itemId);
            Result item = itemClient.getItemById(userInfo[2], itemId);
            Map<String, Object> map = (Map<String,Object>)item.getData();
            int price = (int)map.get("price");
            Long seller = (Long)map.get("createUser");
            sum += price * num;
        }
        Result user = userClient.getUserInfo(userInfo[2]);
        System.out.println(user);
        Map<String,Object> mapUser = (Map<String,Object>)user.getData();
        int money = (int)mapUser.get("money");
        if(money < sum) return Result.error("余额不足");
        else{
            updateMoney upMoney = new updateMoney(Long.parseLong(userInfo[0]),-sum);
            userClient.updateMoney(upMoney);
            //if(true) throw new RuntimeException();
            //mq
            rabbitTemplate.convertAndSend("douyue.topic","pay.success",id);
            //orderMapper.cancelOrder(id);
            log.info("我在这里");
            //TODO: 增加商家的金额
            for(OrderDetail order : orderDetail){
                Long itemId = order.getItemId();
                int num = order.getItemNumber();
                Result item = itemClient.getItemById(userInfo[2], itemId);
                Map<String, Object> map = (Map<String,Object>)item.getData();
                int price = (int)map.get("price");
                int count = price * num;
                Long sellerId = (Long)map.get("createUser");
                pay pay = new pay(sellerId, count);
                System.out.println(pay);
                userClient.pay(pay);
            }
            if(true) throw new RuntimeException();
            //商家mq
            return new Result(0, "支付成功", null);
        }

    }

    @Override
    public Result cancelOrder(Long id) {
        orderMapper.cancelOrder(id);
        return new Result(0, "取消订单成功", null);
    }
}
